import {
    colorUISdk
} from "../../config/mp-sdk";
import {updateCurrentPageShare} from "../../mp-sdk/lib/share";

const app = getApp();
let hasShowedOnce = false;

Page({
    data: {
        scrollTop: 0,
        showResult: false,
        isCorrect: true,
        expanded: false,
        selectAnswer: false,
        iconClass: '',
        // 选项配置
        options: [
            {value: '宝马', label: '宝马', bgClass: 'bg-cyan-gradient', iconClass: ''},
            {value: '玛莎拉蒂', label: '玛莎拉蒂', bgClass: 'bg-cyan-gradient', iconClass: ''},
            {value: '奔驰', label: '奔驰', bgClass: 'bg-cyan-gradient', iconClass: ''}
        ],
        correctAnswer: '奔驰',
        category: '',
        country: '',
        details: '',
        img: ''
    },
    onLoad(options) {
        this.nextQuestion();
    },
    onShow() {
        if (!hasShowedOnce) {
            hasShowedOnce = true;
            return;  // 第一次进入不执行
        }
        this.getUserInfo();
    },
    onHide() {
        //清空数据
        this.setData({
            qrcodeInfo: {}
        });
    },
    //下一题
    nextQuestion() {
        colorUISdk.request({
            url: 'api/user/car_emblem',
            method: 'GET',
            data: {}
        }).then(res => {
            if (res && res.code === 1) {
                let choice = res.data.choice;
                //初始化选项配置options
                let options = [];
                for (const resKey in choice) {
                    let cn_name = choice[resKey];
                    options.push({value: cn_name, label: cn_name, bgClass: 'bg-cyan-gradient', iconClass: ''})
                }
                console.log(options)
                const details = res.data.details.replace(/([。！？])/g, "$1\n");  // 在中文标点后换行
                this.setData({
                    options: options,
                    correctAnswer: res.data.cn_name,
                    expanded: false,
                    selectAnswer: false,
                    isCorrect: true,
                    details: details,
                    img: res.data.img,
                    category: res.data.category,
                    country: res.data.country
                });
            } else {
                wx.showToast({title: res.msg || '失败', icon: 'none'});
            }
        }).catch(err => {
            console.error(err);
            wx.showToast({title: '系统异常', icon: 'none'});
        });
    },
    //返回主页
    goHome() {
        wx.switchTab(
            {url: '/pages/yd_home/home'}
        )
    },
    selectAnswer(e) {
        const value = e.currentTarget.dataset.value;
        const correct = value === this.data.correctAnswer;

        // 遍历选项，只更新当前点击的
        const updatedOptions = this.data.options.map(opt => {
            if (opt.value === value) {
                if (correct) {
                    return {...opt, bgClass: 'bg-green-gradient', iconClass: '_icon-check'};
                } else {
                    return {...opt, bgClass: 'bg-red-gradient', iconClass: '_icon-close'};
                }
            }
            // 其他选项保持原样
            return opt;
        });

        // 更新数据（带延迟效果）
        if (correct) {
            this.setData({selectAnswer: false, isCorrect: correct, options: updatedOptions});
            setTimeout(() => {
                this.setData({selectAnswer: true});
            }, 500);
        } else {
            this.setData({selectAnswer: false, isCorrect: correct, options: updatedOptions});
        }
    },


    toggleExpand() {
        this.setData({expanded: !this.data.expanded});
    },
    getUserInfo() {
        colorUISdk.request({
            url: 'api/user/info',
            method: 'GET',
            data: {}
        }).then(res => {
            if (res && res.code === 1) {
                this.setUserInfo(res.data);
                // 登录成功后立即更新分享配置
                updateCurrentPageShare();
            } else {
                wx.showToast({title: res.msg || '获取失败', icon: 'none'});
            }
        }).catch(err => {
            console.error(err);
            wx.showToast({title: '系统异常', icon: 'none'});
        });
    },
    setUserInfo(data) {
        this.setData({
            userInfo: this.formatUserInfo(data)
        });
        app.userInfo = this.data.userInfo;
    },
    // 格式化接口返回数据，避免空值错误
    formatUserInfo(data) {
        return {
            id: data.id || '',
            avatar: data.avatar || '',
            nickname: data.nickname || ''
        };
    },
    // 监听用户滑动页面事件。
    onPageScroll(e) {
        this.setData({
            scrollTop: e.scrollTop
        })
    }
})